package com.lgc.demo.hashmapTest.myWriteHashMap;

//手写hashMap
public class MyHashMap<K,V> {

    private Node[] theNodes;
    private int size;
    private int THE_NODES_SIZE = 16;

    public MyHashMap() {
        theNodes = new Node[THE_NODES_SIZE];
        size = 0;
    }

    public void put(K key, V value){
        Node node = findNode(key);
        if (node == null) {
            node = new Node(key.hashCode(), key, value, null);
            theNodes[findItemIndex(key)] = node;

            size++;
        }else {
            while (node.next!=null){
                if(node.key.equals(key)){
                    node.value=value;
                    break;
                }

                node = node.next;
            }

            node.next = new Node(key.hashCode(), key, value, null);
            size++;
        }
    }

    public V get(K key){
        Node<K,V> node = findNode(key);
        if (node == null){
            return null;
        }else {
            while (node.next!=null){
                if(node.key.equals(key)){
                    return node.value;
                }
            }

            while (node!=null){
                if(node.key.equals(key)){
                    return node.value;
                }else {
                    node = node.next;
                }
            }

            return null;
        }
    }

    private Node findNode(K key) {
        return theNodes[findItemIndex(key)];
    }

    private int findItemIndex(K key) {
        int hashCode = key.hashCode();
        int nodeIndex = hashCode % THE_NODES_SIZE;
        return nodeIndex;
    }
}
